package com.peng.leetcode.list;

/**
 * SplitListToParts
 *
 * @author: lupeng6
 * @create: 2021/3/5 10:48
 */
public class SplitListToParts {

    public static void main(String[] args) {

    }

    public ListNode[] splitListToParts(ListNode root, int k) {
        ListNode curr = root;
        int len = 0;
        while (curr != null) {
            len++;
            curr = curr.next;
        }

        ListNode[] answer = new ListNode[k];

        int subLen = len / k;
        int offset = len % k;

        curr = root;
        for (int i = 0; i < k; i++) {
            ListNode head = curr;
            for (int j = 0; j < subLen + (i < offset ? 1 : 0) - 1; j++) {
                if (curr != null) {
                    curr = curr.next;
                }
            }
            if (curr != null) {
                ListNode prev = curr;
                curr = curr.next;
                prev.next = null;
            }
            answer[i] = head;
        }
        return answer;
    }
}
